package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.config.Result;
import com.zhentao.pojo.TbBook;
import com.zhentao.service.TbBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 图书查询相关接口
 */
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private TbBookService tbBookService;

    /**
     * 根据 ISBN-13 查询图书信息（直接走本地数据库）
     */
    @GetMapping("/isbn/{isbn13}")
    public Result<TbBook> getByIsbn(@PathVariable("isbn13") String isbn13) {
        if (isbn13 == null || isbn13.length() != 13 || !(isbn13.startsWith("978") || isbn13.startsWith("979"))) {
            return Result.error("ISBN格式不正确，应为以978/979开头的13位数字");
        }

        TbBook book = tbBookService.getOne(new LambdaQueryWrapper<TbBook>()
                .eq(TbBook::getIsbn13, isbn13)
                .last("limit 1"));

        if (book == null) {
            return Result.error("未在本地库找到该图书");
        }
        return Result.success(book);
    }
}